//
//  RMAllergyViewController.m
//  rmplanner
//
//  Created by cs321ga3 on 19/09/12.
//  Copyright (c) 2012 BOSS Systems. All rights reserved.
//

#import "RMAllergyViewController.h"
#import "RMParser.h"

@interface RMAllergyViewController ()

@property (strong, nonatomic) UIAlertView* alertView;

@end

@implementation RMAllergyViewController

static BOOL getting = YES;

@synthesize retData, allergies, selected, ids, indicator, alertView;

#pragma mark UIViewController functions

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	
	getting = YES;
	
	NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/getAllergies"];
	NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
	NSData* data = [[NSString stringWithFormat:@"user_id=%d", [[NSUserDefaults standardUserDefaults] integerForKey:@"uid"]] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	[request setHTTPBody:data];
	[request setHTTPMethod:@"POST"];
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	NSAssert((connection != nil), @"Failed to create a connection");
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	alertView = [[UIAlertView alloc] init];
	alertView.title = @"Loading";
	alertView.frame = CGRectMake(110, 20, 50, 50);
	indicator = [[UIActivityIndicatorView alloc] init];
	indicator.frame = CGRectMake(120, 45, 40, 40);
	[indicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
	[alertView addSubview:indicator];
	[alertView show];
	[indicator startAnimating];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
	    return (interfaceOrientation == UIInterfaceOrientationPortrait);
	else
	    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

#pragma mark UITableViewDataSource delegate functions

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [allergies count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Allergy"];
	//customCell.textLabel.text = [allergies objectAtIndex:indexPath.row];
	
	cell.textLabel.text = [allergies objectAtIndex:indexPath.row];
	
	if ([[selected objectAtIndex:indexPath.row] boolValue])
	{
		cell.accessoryType = UITableViewCellAccessoryCheckmark;
	}
	else
		cell.accessoryType = UITableViewCellAccessoryNone;
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	if ([[selected objectAtIndex:indexPath.row] isEqualToNumber:[NSNumber numberWithBool:NO]])
	{
		[selected replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
	}
	else
	{
		[selected replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:NO]];
	}
	[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
	[self.tableView reloadData];
}

#pragma mark NSURLConnection delegate functions

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	retData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[retData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	[indicator stopAnimating];
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	connection = nil;
	
	if (getting)
	{
		RMParser* parser = [[RMParser alloc] init];
		[parser specialParse:retData settings:self];
		NSLog(@"%@", [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding]);
		[self.tableView reloadData];
	}
	else
	{
		NSLog(@"%@", [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding]);
		[self.navigationController popViewControllerAnimated:YES];
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSLog(@"%@", [error description]);
	connection = nil;
	UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:@"Connection to server failed. Try again later" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
}

#pragma mark UIAlertView delegate functions

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark Interface Builder actions

- (IBAction)save
{
	getting = NO;
	NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/saveAllergies"];
	NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
	NSMutableString* argStr = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"user_id=%d", [[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] intValue]]];
	NSLog(@"%d", [allergies count]);
	for (int i = 0; i < [allergies count]; i++)
	{
		if ([[selected objectAtIndex:i] isEqualToNumber:[NSNumber numberWithBool:YES]])
		{
			[argStr appendFormat:@"&allergies[]=%d", [[ids objectAtIndex:i] intValue]];
		}
	}
	NSData* data = [argStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	[request setHTTPBody:data];
	[request setHTTPMethod:@"POST"];
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	NSAssert((connection != nil), @"Failed to create a connection");
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

@end
